﻿using System.Security.Claims;
using Furion.DataEncryption;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Authorization;
using 微信信息管理系统.Code.Model;

namespace 微信信息管理系统.Code.Service;

[AppAuthorize]
public class AdminUserService : IDynamicApiController
{
    private readonly IFreeSql _fsql;

    public AdminUserService(IFreeSql fsql)
    {
        _fsql = fsql;
    }

    // 获取分页列表
    public async Task<Res<PageResult<AdminUser>>> PostPage(PageInput input)
    {
        var query = _fsql.Select<AdminUser>();
        if (!string.IsNullOrEmpty(input.Keywords))
        {
            query.Where(x =>
                x.UserName.Contains(input.Keywords) ||
                x.Remark.Contains(input.Keywords)
            );
        }

        var result = await query.OrderByDescending(x => x.Id).Count(out long count).Page(input.Page, input.PerPage).ToListAsync();

        return new Res<PageResult<AdminUser>>(new PageResult<AdminUser>
            {
                count = (int) count,
                rows = result
            }
        );
    }

    public async Task<object> GetInfo()
    {
        return new {UserName = Furion.App.User.FindFirstValue("UserName"), UserId = Furion.App.User.FindFirstValue("Id")};
    }

    [AllowAnonymous]
    public async Task<Res<object>> PostLogin(AdminUser AdminUser)
    {
        var any = await _fsql.Select<AdminUser>().Where(x => x.UserName == AdminUser.UserName && x.Password == AdminUser.Password).ToOneAsync();
        if (any == null)
        {
            return new Res<object>("用户名或密码错误", false);
        }

        // Furion jwt授权
        var accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>()
        {
            {"Id", any.Id},
            {"UserName", any.UserName},
        });
// 获取刷新 token
        var refreshToken = JWTEncryption.GenerateRefreshToken(accessToken, 60 * 24 * 30); // 第二个参数是刷新 token 的有效期（分钟），默认三十天

        return new Res<object>(new {token = accessToken, xtoken = refreshToken});
    }

    public async Task<Res<AdminUser>> Get(int id)
    {
        var AdminUser = await _fsql.Select<AdminUser>().Where(x => x.Id == id).ToOneAsync();
        return new Res<AdminUser>(AdminUser);
    }

    public async Task<Res<AdminUser>> Post(AdminUser AdminUser)
    {
        try
        {
            var result = await _fsql.Insert<AdminUser>(AdminUser).ExecuteAffrowsAsync();
            return new Res<AdminUser>(AdminUser);
        }
        catch (Exception e)
        {
            return new Res<AdminUser>("信息已经提交过了！", false);
        }
    }

    public async Task<Res<AdminUser>> Put(AdminUser input)
    {
        var fq = _fsql.Update<AdminUser>();
        fq.SetIf(!string.IsNullOrWhiteSpace(input.Password), it => it.Password == input.Password);
        fq.Set(it => it.Remark == input.Remark);

        var result = await fq.Where(it => it.Id == input.Id).ExecuteAffrowsAsync();
        return new Res<AdminUser>();
    }

    public async Task<Res<AdminUser>> Delete(int id)
    {
        var result = await _fsql.Delete<AdminUser>(id).ExecuteAffrowsAsync();
        return new Res<AdminUser>(null);
    }
}